
package com.eportal.action.background;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import com.alipay.api.domain.ArrangementBaseSelector;
import com.eportal.action.BaseAction;
import com.eportal.domain.CBuilding;
import com.eportal.domain.CInstallUnit;
import com.eportal.domain.CRoom;
import com.eportal.domain.RoomUser;
import com.eportal.domain.Sysopt;
import com.eportal.domain.Sysroles;
import com.eportal.domain.TCommunity;
import com.eportal.domain.TLock;
import com.eportal.domain.User;
import com.eportal.service.CBuildingService;
import com.eportal.service.CInstallUnitService;
import com.eportal.service.CRoomService;
import com.eportal.util.IDCard;
import com.eportal.util.ValidateUtil;
import com.eportal.util.WebUtil;
import com.framework.excelTools.ExcelUtil;
import com.framework.jqgrid.JqGridPager;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.opensymphony.xwork2.ModelDriven;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

/**
 * 房间管理
 * @author chencheng
 *
 */
public class CRoomAction extends BaseAction implements ModelDriven<CRoom> {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Logger log = Logger.getLogger(CRoomAction.class);

    private Map<String, Object> result = new HashMap<String, Object>();
    
    @Autowired
    private CRoomService cRoomService;
    @Autowired
    private CInstallUnitService cInstallUnitService;
    @Autowired
    private CBuildingService cBuildingService;
	/**
     * 房间管理
     */
    public String listView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 1) {
    		getRequest().setAttribute("communityId", getRequest().getParameter("communityId"));
    	}else{
    		getRequest().setAttribute("communityId", "");
    	}
        return SUCCESS;
    }
    
    /**
     * 房间住户列表
     */
    public  void listUser() throws Exception{
    	JqGridPager page = new JqGridPager();
    	String roomId = getRequest().getParameter("sid");
    	StringBuilder where = new StringBuilder(" t.room_id='");
    	where.append(roomId);
    	where.append("' and t.utype in ('3','4')");
    	page.setWhere(where.toString());
    	setPage(getRequest(), page);
    	page.setSidx("utype");
    	page.setSord("asc");
        List<RoomUser> users = cRoomService.listUser(page);
        jqGridQueryMap(Sysroles.class, getRequest(), users, getResponse(), page);

    }
    
    //获取房间
    public void list2() throws Exception{
    	String unitId = getRequest().getParameter("unitId");
    	StringBuilder where = new StringBuilder(" where 1=1 ");
		where.append(" and unitId ='");
		where.append(unitId);
		where.append("'");
        List<CRoom> cRooms = cRoomService.list(where.toString());
        responseBody(cRooms);
    }
    /**
     * 房间列表
     */
    public void list() throws Exception {
        JqGridPager page = new JqGridPager();
        Sysopt  user= (Sysopt)getSession().getAttribute("user");
        String communityId = getRequest().getParameter("communityId");
	 	if (StringUtils.isBlank(communityId)) {
	 		communityId = user.getCommunityId();
		}
	 	String cBuildingId = getRequest().getParameter("cBuildingId");
    	String unitId = getRequest().getParameter("unitId");
    	String roomNo = getRequest().getParameter("roomNo");
    	String ownerName = getRequest().getParameter("ownerName");
    	String tel = getRequest().getParameter("tel");
    	String idNo = getRequest().getParameter("idNo");
	 	
    	StringBuilder where = new StringBuilder(" t.communityid='");
    	where.append(communityId);
    	where.append("'");
    	if (!StringUtils.isBlank(cBuildingId)) {
    		where.append(" and b.sid = '");
    		where.append(cBuildingId);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(unitId)) {
    		where.append(" and u.sid = '");
    		where.append(unitId);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(roomNo)) {
    		where.append(" and t.room_no like '%");
    		where.append(roomNo);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(ownerName)) {
    		where.append(" and t.owner_name like '%");
    		where.append(ownerName);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(tel)) {
    		where.append(" and t.owner_tel = '");
    		where.append(tel);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(idNo)) {
    		where.append(" and t.owner_id_number like '%");
    		where.append(idNo);
    		where.append("%'");
    	}
    	page.setWhere(where.toString());
    	setPage(getRequest(), page);
        List<CRoom> cRooms = cRoomService.list(page);
        jqGridQueryMap(Sysroles.class, getRequest(), cRooms, getResponse(), page);
    }
    
    
    /**
     * 公告页面，列出所有单元下业主姓名手机号
     * 所有的楼栋单元列表
     */
    public void listRoom() throws Exception {
    	String unit = getRequest().getParameter("unit");
    	String budingid = getRequest().getParameter("sid");
    	List<Map<String, Object>> listroom = cRoomService.queryBySql(unit,budingid);
        responseBody(listroom);
    }

    
    /**
     * 房间新增
     */
    public String addView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 1) {
    		getRequest().setAttribute("communityId", getRequest().getParameter("communityId"));
    	}else{
    		getRequest().setAttribute("communityId", "");
    	}
        return SUCCESS;
    }
    
    public String importView() {
        return SUCCESS;
    }
    
    String[] titles = {"楼栋","单元","房间号","房间编号","手机*","姓名*","身份证"};
    
    public String export() {
    	Map map = new HashMap();
    	try{
    		int userRole =  (Integer) getSession().getAttribute("userRole");
    		if(userRole==5||userRole==6){
    			Sysopt  user= (Sysopt)getSession().getAttribute("user");
    			
    			List dataList = new ArrayList();
    			dataList.add(titles);
    	        List<Map<String, String>> list = cRoomService.listBySql("select t.*,u.cbname as unitName,b.cbname from T035_ROOM t left join t032_cinstallunit u on t.unit_id=u.sid left join t031_cbuilding b on u.cbuildingid=b.sid where t.communityid='"+user.getCommunityId()+"'");
    	        for(Map m:list){
    	        	List subList = new ArrayList();
    	        	subList.add(m.get("CBNAME"));
    	        	subList.add(m.get("UNITNAME"));
    	        	subList.add(m.get("ROOM_NO"));
    	        	subList.add(m.get("SID"));
    	        	dataList.add(subList.toArray());
    	        }
    	        HttpServletResponse response = getResponse();
    	        response.reset();            
    	        response.setContentType("application/vnd.ms-excel");        //改成输出excel文件  
    	        response.setHeader("Content-disposition","attachment; filename="+System.currentTimeMillis()+".xls" );
    	        ExcelUtil.export("room", dataList, response.getOutputStream());
    		}else{
    			log.info("用户角色不正确，无法导出数据,userRole="+userRole);
    		}
    	}catch(Exception e){
    		log.error(this, e);
    		map.put("code", "-1");
			map.put("msg", "导出数据繁忙");
    	}
    	return null;
    }
   
    /**
     * 导入数据
     */
	public void importDa() {
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
		int userRole =  (Integer) getSession().getAttribute("userRole");
		Map result = new HashMap();
		String type = getRequest().getParameter("type");
		if (type == null || type.trim().length() < 1) {
			result.put("code", 0);
			result.put("msg", "请选择类型");
			responseBody(result);
			return;
		}
		List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();
		try {
			File file = getUpload();
			// String fileName = getUploadFileName();
			FileInputStream fis = null;
			fis = new FileInputStream(file);

			// 根据Excel数据源创建WorkBook
			Workbook wb = Workbook.getWorkbook(fis);
			// 获取工作表
			Sheet sheet = wb.getSheet(0);

			for (int j = 0; j < titles.length; j++) {
				Cell currentCell = sheet.getCell(j, 0);
				String str = currentCell.getContents();
				if (!str.equals(titles[j])) {
					result.put("code", 0);
					result.put("msg", "格式不正确，请检查导入文件");
					responseBody(result);
					return;
				}

			}
			// 获取工作表的有效行数
			int realRows = 0;
			for (int i = 1; i < sheet.getRows(); i++) {
				Map map = new HashMap();
				int nullCols = 0;
				String roomNo = null;
				String sid = null;
				String tel = null;
				String name = null;
				String idcard = null;
				for (int j = 1; j < titles.length; j++) {
					Cell currentCell = sheet.getCell(j, i);
					String str = currentCell.getContents();
					if (j == 2) {
						roomNo = str;
					} else if (j == 3) {
						sid = str;
					} else if (j == 4) {
						tel = str;
					} else if (j == 5) {
						name = str;
					} else if (j == 6) {
						idcard = str;
					}
				}
				int rowName=i+1;

				if (roomNo == null || roomNo.trim().length() < 1) {
					result.put("code", 0);
					result.put("msg", "第" + rowName + "行房间号为空");
					responseBody(result);
					return;
				}
				if (sid == null || sid.trim().length() < 1) {
					result.put("code", 0);
					result.put("msg", "第" + rowName + "行房间编号为空");
					responseBody(result);
					return;
				}
				if (tel == null || tel.trim().length() < 1) {
					break;
				} else if (name == null || name.trim().length() < 1) {
					result.put("code", 0);
					result.put("msg", "第" + rowName + "行姓名为空");
					responseBody(result);
					return;
				}
				map.put("roomNo", roomNo);
				map.put("sid", sid);
				map.put("tel", tel);
				map.put("name", name);
				map.put("idcard", idcard);
				map.put("i", String.valueOf(rowName));
				dataList.add(map);

				if (nullCols == sheet.getColumns()) {
					break;
				} else {
					realRows++;
				}
			}
			for(Map<String,String> m:dataList){
				String sid = m.get("sid");
				String i = m.get("i");
				CRoom room =  cRoomService.get(Long.valueOf(sid));
				if(!room.getRoomNo().equals(m.get("roomNo"))){
					result.put("code", 0);
					result.put("msg", "第" + i + "行房间数据不符");
					responseBody(result);
					return;
				}
				if(user.getCommunityId().equals(room.getCommunityId())){
					result=cRoomService.addRoomUser(room.getCommunityId(),sid, m.get("name"), m.get("tel"), m.get("idcard"), type);
				}else{
					result.put("code", 0);
					result.put("msg", "房间编号:"+sid+",无权限修改");
					responseBody(result);
					return;
				}
			}

		} catch (Exception e) {
			result.put("code", 0);
			result.put("msg", "导入失败");
			responseBody(result);
			log.error(this, e);
			return;
		}

		responseBody(result);
		return;
	}
    /**
     * 房间住户新增
     */
    public String addUserView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 1) {
    		getRequest().setAttribute("communityId", getRequest().getParameter("communityId"));
    	}else{
    		getRequest().setAttribute("communityId", "");
    	}
        return SUCCESS;
    }
    //房间住户保存
    public void addUser(){
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String communityId = getRequest().getParameter("communityId");
  	 	if (StringUtils.isBlank(communityId)) {
  	 		communityId = user.getCommunityId();
  		} 
  	 	String roomId = getRequest().getParameter("sid");
    	String userName = getRequest().getParameter("userName");
    	String userTel = getRequest().getParameter("userTel");
    	String userIdNumber = getRequest().getParameter("userIdNumber");
    	String status = getRequest().getParameter("status");
    	result=cRoomService.addRoomUser(communityId, roomId, userName, userTel, userIdNumber, status);
    	responseBody(result);
    }
    /**
     * 房间新增保存
     */
    public void add(){
    	String msg = ValidateUtil.validate(getModel());
        if (msg == null || msg.trim().length() == 0) {
	    	CRoom cRoom = getModel();
	    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
	    	String communityId = getRequest().getParameter("communityId");
	  	 	if (StringUtils.isBlank(communityId)) {
	  	 		communityId = user.getCommunityId();
	  		}
	  	 	cRoom.setCommunityId(communityId);
	  	 	result = checkCRoom(cRoom);
	  	 	if (!"1".equals(result.get("code").toString())) {
	  	 		responseBody(result);
	  	 		return;
			}
	  	 	result = cRoomService.addMethod(cRoom);
        } else {
            result.put("msg", msg);
        }
        responseBody(result);
    }
    
    private Map<String, Object> checkCRoom(CRoom cRoom) {
    	result = new HashMap<String, Object>();
    	String regex = "^1[3|4|5|7|8]\\d{9}$";
		if(!Pattern.matches(regex, cRoom.getOwnerTel())){
			 result.put("code", 0);
	         result.put("msg", "户主手机号填写格式不正确");
	         return result;
		}
		if(cRoom.getOwnerIdNumber()!=null&&cRoom.getOwnerIdNumber().length()>0&&!IDCard.validateIdCard(cRoom.getOwnerIdNumber())){
			 result.put("code", 0);
	         result.put("msg", "户主身份证号填写不正确");
	         return result;
		}
		if ("2".equals(cRoom.getStatus())) {
			if (StringUtils.isBlank(cRoom.getRenterName())) {
				 result.put("code", 0);
		         result.put("msg", "租客姓名必填");
		         return result;
			}
			if (StringUtils.isBlank(cRoom.getRenterTel())) {
				 result.put("code", 0);
		         result.put("msg", "租客手机必填");
		         return result;
			}else if(!Pattern.matches(regex, cRoom.getRenterTel())){
				 result.put("code", 0);
		         result.put("msg", "租客手机号填写格式不正确");
		         return result;
			}
			if(cRoom.getRenterIdNumber()!=null&&cRoom.getRenterIdNumber().length()>0&&!IDCard.validateIdCard(cRoom.getRenterIdNumber())){
				 result.put("code", 0);
		         result.put("msg", "租客身份证号填写不正确");
		         return result;
			}
		}
		result.put("code",1);
		return result;
		
	}

	/**
     * 房间修改
     */
    public String editView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 1) {
    		getRequest().setAttribute("communityId", getRequest().getParameter("communityId"));
    	}else{
    		getRequest().setAttribute("communityId", "");
    	}
    	Map<String, String> map =  cRoomService.getRoom(getModel().getSid());
        getRequest().setAttribute("cRoom", map);
        return SUCCESS;
    }
    
    
	/**
     * 房间修改
     */
    public String editViewV2() {
    	try{
    		int userRole =  (Integer) getSession().getAttribute("userRole");
        	if (userRole == 1) {
        		getRequest().setAttribute("communityId", getRequest().getParameter("communityId"));
        	}else{
        		getRequest().setAttribute("communityId", "");
        	}
        	Map<String, Object> map = new HashMap();
        	
        	CRoom room = cRoomService.get(cRoom.getSid());
        	CInstallUnit unit = cInstallUnitService.get(Long.valueOf(room.getUnitId()));
      	 	CBuilding building = cBuildingService.get(Long.valueOf(unit.getcBuildingId()));
      	 	map.put("unitName", unit.getCbName());
      	 	map.put("cBuildingName", building.getCbName());
      	 	map.put("sid", room.getSid());
      	 	map.put("room_no", room.getRoomNo());
      	 	map.put("floor_no", room.getFloorNo());
      	 	map.put("unitSid", room.getUnitId());
      	 	map.put("buidingSid", building.getSid());
            getRequest().setAttribute("cRoom", map);
            return SUCCESS;
    	}catch(Exception e){
    		log.error(this, e);
    		return ERROR;
    	}
    	
    }
    
    
    /**
     * 房间更新保存
     */
    public void update(){
    	String msg = ValidateUtil.validate(getModel());
        if (msg == null || msg.trim().length() == 0) {
	    	CRoom cRoom = getModel();
	    	result = checkCRoom(cRoom);
	  	 	if (!"1".equals(result.get("code").toString())) {
	  	 		responseBody(result);
	  	 		return;
			}
	    	result = cRoomService.updateMethod(cRoom);
        } else {
            result.put("msg", msg);
        }
        responseBody(result);
    }

    
    /**
     * 房间更新保存
     */
    public void updateV2(){
    	try{
    		Sysopt  user= (Sysopt)getSession().getAttribute("user");
	    	CRoom cRoom = getModel();
	  	 	String cBuildingName = getRequest().getParameter("cBuildingName");
	  	 	String unitName = getRequest().getParameter("unitName");
	  	 	
	  	 	CRoom old = cRoomService.get(cRoom.getSid());
	  	 	CInstallUnit unit = cInstallUnitService.get(Long.valueOf(old.getUnitId()));
	  	 	CBuilding building = cBuildingService.get(Long.valueOf(unit.getcBuildingId()));
	  	 	String communityid  = user.getCommunityId();
	  	 	CBuilding newBuild  = null;
	  	 	CInstallUnit newUnit = null;
	  	 	if(communityid==null){
	  	 		result.put("code", 0);
  				result.put("msg", "请使用小区账号操作");
  				responseBody(result);
  				return;
	  	 	}
	  	 	if(!cBuildingName.equals(building.getCbName())){
	  	 		List<CBuilding> list = cBuildingService.list("where cbName='"+cBuildingName+"' and communityid='"+communityid+"'");
	  	 		if(list.size()==0){
	  	 			newBuild  = new CBuilding();
	  	 			newBuild.setCbName(cBuildingName);
	  	 			newBuild.setCommunityId(communityid);
	  	 			newBuild.setcTime(new Timestamp(System.currentTimeMillis()));
	  	 			newBuild.setuUserName(String.valueOf(user.getSid()));
	  	 			newBuild.setComm("修改房间时创建，roomid="+cRoom.getSid());
	  	 			cBuildingService.add(newBuild);
	  	 			newUnit = new CInstallUnit();
	  	 			newUnit.setCbName(unitName);
	  	 			newUnit.setcBuildingId(String.valueOf(newBuild.getSid()));
	  	 			newUnit.setcTime(new Timestamp(System.currentTimeMillis()));
	  	 			newUnit.setComm("修改房间时创建，roomid="+cRoom.getSid());
	  	 			newUnit.setcUserName(user.getSid().toString());
	  	 			cInstallUnitService.add(newUnit);
	  	 			
	  	 		}else if(list.size()==1){
	  	 			newBuild  = list.get(0);
  	 				List<CInstallUnit> unitList = cInstallUnitService.list("where cbName='"+unitName+"' and cBuildingId='"+newBuild.getSid()+"'");
  	 				if(unitList.size()==0){
  	 					newUnit = new CInstallUnit();
  	 					newUnit.setCbName(unitName);
  	 					newUnit.setcBuildingId(String.valueOf(newBuild.getSid()));
  	 					newUnit.setcTime(new Timestamp(System.currentTimeMillis()));
  	 					newUnit.setComm("修改房间时创建，roomid="+cRoom.getSid());
  	 					newUnit.setcUserName(user.getSid().toString());
  		  	 			cInstallUnitService.add(newUnit);
  	 				}else if(unitList.size()==1){
  	 					newUnit = unitList.get(0);
  	 				}else{
  	 					result.put("code", 0);
  		  				result.put("msg", "单元数据重复，请重新确认");
  		  				responseBody(result);
  		  				return;
  	 				}
	  	 		}else{
	  	 			result.put("code", 0);
	  				result.put("msg", "楼栋数据重复，请重新确认");
	  				responseBody(result);
	  				return;
	  	 		}
	  	 		
	  	 	}else if(!unitName.equals(unit.getCbName())){
	  	 			newBuild = building;
	 				List<CInstallUnit> unitList = cInstallUnitService.list("where cbName='"+unitName+"' and cBuildingId='"+newBuild.getSid()+"'");
	 				if(unitList.size()==0){
	 					newUnit = new CInstallUnit();
	 					newUnit.setCbName(unitName);
	 					newUnit.setcBuildingId(String.valueOf(newBuild.getSid()));
	 					newUnit.setcTime(new Timestamp(System.currentTimeMillis()));
	 					newUnit.setComm("修改房间时创建，roomid="+cRoom.getSid());
		  	 			cInstallUnitService.add(newUnit);
	 				}else if(unitList.size()==1){
	 					newUnit = unitList.get(0);
	 				}else{
	 					result.put("code", 0);
		  				result.put("msg", "单元数据重复，请重新确认");
		  				responseBody(result);
		  				return;
	 				}
	 			
	  	 	}else{
	  	 		newBuild = building;
	  	 		newUnit = unit;
	  	 	}
	  	 	
	  	 	CRoom room = cRoomService.get(cRoom.getSid());
	  	 	room.setUnitId(newUnit.getSid().toString());
	  	 	room.setuTime(new Timestamp(System.currentTimeMillis()));
	  	 	room.setuUserName(user.getSid().toString());
	  	 	room.setFloorNo(cRoom.getFloorNo());
	  	 	room.setRoomNo(cRoom.getRoomNo());
	  	 	List elist = cRoomService.list(" where unitId = '"+room.getUnitId()+"' and roomNo='"+room.getRoomNo()+"' and sid != "+room.getSid());
        	if(elist.size()>0){
        		result.put("code", 0);
		        result.put("msg", "该单元下房间名称已存在，请修改后保存");
		        responseBody(result);
		        return;
        	}
	    	cRoomService.update(room);
	    	result.put("code", 1);
	        result.put("msg", "操作成功");
            responseBody(result);
    	}catch(Exception e){
    		result.put("code", 0);
			result.put("msg", "操作失败");
			responseBody(result);
    		log.error(this, e);
    	}
    	
    }
    /**
     * 房间删除
     */
    public void delete() {
    	Sysopt  user = (Sysopt)getSession().getAttribute("user");
    	String param_ids = getRequest().getParameter("ids");
    	try{
    		result = cRoomService.deleteMethod(param_ids,user.getCommunityId());	
    	}catch(Exception e){
    		result.put("code", 0);
			result.put("msg", "操作失败");
    		log.error(this,e);
    	}
    	
        responseBody(result);
    }

    /**
     * 房间住户删除
     */
    public void deleteUser() {
    	String sid = getRequest().getParameter("sid");
    	result = cRoomService.deleteUser(sid);
        responseBody(result);
    }
    private CRoom cRoom = new CRoom();

    @Override
    public CRoom getModel() {
        return cRoom;
    }
}
